const fs = require("fs");
//获取插件
function loadPlugin(app) {
  const plugins = require(__dirname + "/../../../config/plugin");
  const pluginArr = [];
  //获取组件配置、组件所在目录
  for (let name in plugins) {
    pluginArr.push({
      name,
      packageName: plugins[name],
      config: app.config[name] || null,
      path: getPluginPath(plugins[name]),
    });
  }
  //实例化组件
  pluginArr.forEach((p) => {
    const { start } = require(p.path + "/index");
    start(app, p.config);
  });
}
function getPluginPath(packageName) {
  const basePath = __dirname + "/../../../node_modules/";
  if (fs.existsSync(basePath + packageName)) return basePath + packageName;
  else throw new Error(`plugin [${packageName}] not found!`);
}
module.exports = { loadPlugin };
